<?php
namespace App\Service\Classes;

use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpKernel\Log\Logger;

class Sms
{

    const expire_at = 15;
    const template  = 'SMS_171040807';

    /**
     * 发送
     *
     * @param [type] $tel
     * @return string|boolean
     */
    public function send($tel)
    {
        $code    = $this->generate_code();
        $easySms = new EasySms(config('easysms'));
  
        $easySms->send($tel, [
            'template' => self::template,
            'data' => [
                'code' => $code
            ],
        ]);
        $key = 'verificationCode_' . str_random(15);
        $expiredAt = now()->addMinutes(self::expire_at);
        Cache::put($key, $code, $expiredAt);
        
        return $key;
    }

    /**
     * 检查验证码
     *
     * @param [type] $key
     * @param [type] $inputCode
     * @return void
     */
    public function check($key, $inputCode)
    {
        if(app()->environment() != 'production'){
            return true;
        }
        $verifyData = Cache::get($key);
        if (!$verifyData) {
            return false;
        }
        if (!hash_equals($inputCode, $verifyData['code'])) {
            return false;
        }
        return true;
    }


    /**
     * 生成验证码
     *
     * @return void
     */
    private function generate_code()
    {
        return str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
    }
}
